/*
 * File Name:               ProtoBufExtension.cs
 * 
 * Description:             普通类
 * Author:                  zhangke <kris@zhanng.org>

 * Create Date:             2017/06/02
 */

using System.Reflection;
using System.Collections;


public static class ProtoBufExtension
{
    public static string ToJson(this ProtoBuf.IExtensible pb)
    {
        var type = pb.GetType();
        var properties = type.GetProperties();
        if (properties != null)
        {
            var sb = new System.Text.StringBuilder();
            sb.Append("{");
            for (int i = 0; i < properties.Length; i++)
            {
                var p = properties[i];
                var obj = p.GetValue(pb, null);
                if (obj is ProtoBuf.IExtensible)
                    sb.Append(string.Format("\"{0}\":{1}", p.Name, ((ProtoBuf.IExtensible)obj).ToJson()));
                else if (obj is IList)
                {
                    sb.Append(string.Format("\"{0}\":[", p.Name));
                    var lst = (IList)obj;
                    for (int j = 0; j < lst.Count; j++)
                    {
                        var item = lst[j];
                        var t = item.GetType();
                        if (item is ProtoBuf.IExtensible)
                            sb.Append(((ProtoBuf.IExtensible)item).ToJson());
                        else if (t == typeof(System.String))
                            sb.Append(string.Format("\"{0}\"", item));
                        else if (p.PropertyType == typeof(System.Boolean))
                        {
                            var content = item.ToString();
                            if (content == "False") content = "false";
                            else if (content == "True") content = "true";
                            sb.Append(content);
                        }
                        else
                            sb.Append(string.Format("{0}", item));

                        if (j < lst.Count - 1) sb.Append(",");
                    }

                    sb.Append("]");
                }
                else if (p.PropertyType == typeof(System.String))
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\"", p.Name, obj.ToString().Replace("False", "false")));
                }
                else if (p.PropertyType == typeof(System.Boolean))
                {
                    var content = obj.ToString();
                    if (content == "False") content = "false";
                    else if (content == "True") content = "true";
                    sb.Append(string.Format("\"{0}\":{1}", p.Name, content));
                }
                else
                    sb.Append(string.Format("\"{0}\":{1}", p.Name, obj));

                if (i < properties.Length - 1) sb.Append(",");
            }
            sb.Append("}");
            return sb.ToString();
        }

        return "[error] display pb data content fail. ";
    }

}
